package com.ssyc.gsk_tk.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.gsk_tk.R;
import com.ssyc.gsk_tk.bean.AnswerInfo;
import com.ssyc.gsk_tk.bean.ReadShowAnswerInfo;
import com.ssyc.gsk_tk.util.TkKeys;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选词填句子答案的Framgent
 * Created by Administrator on 2018/9/4 0004.
 */

public class TkGapFillingAnswerFragment extends LazyBaseFragment {

    //页面的数据模型
    private AnswerInfo articleInfo;

    //题号
    private int quesPos;

    //当前题目正确答案
    private String rightAnswer;

    /*完成状态下需要显示的相关布局*/
    //展示以完成状态下的线性整体布局
    private LinearLayout llShowAnswer;
    //文章内容
    private TextView tvArticle;

    //展示自己答案的列表
    private MyListView lvOwnAnswer;
    //展示正确答案的列表
    private MyListView lvRightAnswer;
    //正确率
    private TextView tv_answer_present;
    //解析
    private TextView tvParseAnswer;

    //切割字符串的下划线
    private static final String regx = "__";

    //你的答案
    private TextView tv_own_answer;
    //正确答案
    private TextView tv_right_answer;
    //解析
    private TextView tv_parse_answer;


    //切割的正则表达式,以2个下划线开头并且以2个下划线结尾,中间可以是任意字母和数字不限制个数
    private String reg = "_{1}[_]+_{1}";
//    private String reg = "_{2}[0-9a-zA-Z]+_{2}";
    //使用正则表达式切割后的字符串集合
    private String[] sentences;
    //用于保存用户输入的内容,初始值为服务器返回的__i__
    private Map<Integer, String> inputContent;

    //是否完成的标识
    private int state;

    public static final TkGapFillingAnswerFragment newInstance(AnswerInfo info,int pos, int state) {
        TkGapFillingAnswerFragment tkReadChooseAnswerFragment = new TkGapFillingAnswerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("pos", pos);
        bundle.putSerializable("data", info);
        bundle.putInt("state", state);
        tkReadChooseAnswerFragment.setArguments(bundle);



        return tkReadChooseAnswerFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tk_gap_filling_answer;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        //显示内容
        showContent();

        //获取页面数据
        initIntent();

        //初始化视图
        initView(view);

        //同步底部文章数据的方法
        intiStateBottom();
    }


    /**
     * 获取页面数据
     */
    private void initIntent() {
        articleInfo = (AnswerInfo) getArguments().getSerializable("data");
        quesPos =  getArguments().getInt("pos");
        state = getArguments().getInt("state");
        rightAnswer = articleInfo.rightAnswer;


    }

    /**
     * 初始化视图
     * @param view
     */
    public void initView(View view) {
        tvArticle = view.findViewById(R.id.tv_article);
        lvOwnAnswer = view.findViewById(R.id.lv_own_answer);
        lvRightAnswer = view.findViewById(R.id.lv_right_answer);
        tv_answer_present = view.findViewById(R.id.tv_answer_present);
        tvParseAnswer = view.findViewById(R.id.tv_parse_answer);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        tv_right_answer = view.findViewById(R.id.tv_right_answer);
        tv_own_answer = view.findViewById(R.id.tv_own_answer);
        if (state == 0) {
            //未完成
            llShowAnswer.setVisibility(View.GONE);
            //未完成列表选项可以点击
        } else if (state == 1) {
            //以完成
            llShowAnswer.setVisibility(View.VISIBLE);

            //展示问题的TextView不需要点击事件
            tvArticle.setEnabled(false);
            //以完成列表选项可以点击
            //初始化你的作答,正确答案,答案正确率和解析
            initHasCompetedData();
        }
    }

    /**
     * 采用正则表达式切割服务器返回的答案
     */
    private void intiStateBottom() {
        if (articleInfo != null && !TextUtils.isEmpty(articleInfo.qustionContent)) {
            //服务器返回的文章的内容
            String articleContent = articleInfo.qustionContent;

            //采用切割的方式来实现,采用正则表达式__任意数字和字母__ 正则表达式来切割来切割
            sentences = articleContent.split(reg);

            //初始化创建Map用以保存输入的内容,默认值是__i__
            inputContent = new HashMap<>();
            inputContent.put(0, "__" +  "__");

            sysTvArticleContentState();
        }
    }

    /**
     * 同步点击事件的方法
     */
    private void sysTvArticleContentState() {

        String content = "";

        //拼接需要显示的字符串
        //以__结尾,切割的数组长度和填空的位置一样
        //不以__结尾的话,切割的字符串数组长度比需要填空的位置多一个
        if (sentences.length == inputContent.size()) {
            //以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                if (!TextUtils.isEmpty(inputContent.get(i))) {
                    content += sentences[i] + inputContent.get(i);
                }
            }
        } else {
            //不以__结尾的话,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + inputContent.get(i);
            }
            content += sentences[sentences.length - 1];
        }

        //计算需要变色的位置
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
        for (int i = 0; i < inputContent.size(); i++) {
            //定义变量记录点击的位置
            int index = i;
            //第一个变色位置的开始坐标sentences[0].length()
            //第一个变色结束的位置 sentences[0].length() + inputContent.get(0).length
            //第二个变色位置的开始坐标sentences[0].length()+inputContent.get(0).length()+sentences[1].length()
            //第二个变色的结束位置 start+inputContent.get(1).length
            //第三个变色位置的开始坐标sentences[0].length()+inputContent.get(0).length()+sentences[1].length()+inputContent.get(1).length()
            int start = 0;
            int end = 0;
            if (i == 0) {
                start = sentences[0].length();
                end = start + inputContent.get(0).length();
            } else {
                for (int j = 0; j <= i; j++) {
                    start += sentences[j].length();
                }
                for (int k = 0; k <= i - 1; k++) {
                    start += inputContent.get(k).length();
                }

                end = start + inputContent.get(i).length();
            }

            stringBuilder.setSpan(new TkGapFillingAnswerFragment.TextClick() {
                @Override
                public void onClick(View view) {
                    Log.i("test", "被点击的位置是:" + index);
                    showInputPop(index);
                }
            }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        tvArticle.setText(stringBuilder);

        //设置该方法后,点击事件才能生效
        tvArticle.setMovementMethod(LinkMovementMethod.getInstance());

    }


    /**
     * 点击空格位置弹出输入框的方法
     *
     * @param index
     */
    private void showInputPop(int index) {
        PopUpManager.showPop(getContext(), R.layout.tk_pop_input_form_blank, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //取消
                TextView tvCancel = view.findViewById(R.id.tv_cancel);
                //保存
                TextView tvOk = view.findViewById(R.id.tv_ok);
                //输入框
                EditText etInput = view.findViewById(R.id.et_input);

                //提示
                TextView tvMsg = view.findViewById(R.id.tv_pop_content);
                tvMsg.setText("请输入答案");

                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //关闭弹框
                        PopUpManager.dismiss();
                    }
                });

                tvOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //点击确定后的操作
                        //第一步:获取输入框的文字,进行非空判断
                        String content = etInput.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            //没有输入单词
                            UiUtils.Toast("您还没有输入单词", false);
                            return;
                        } else {
                            //已经输入了单词
                            //第二步:将输入的单词回显到点击的空格位置

                            //将用于保存输入框的内容的集合中点击的位置的值进行同步
                            inputContent.put(index, regx + content + regx);
                            Log.i("test", "获取到的点击的位置是:" + index);

                            //再次设置点击事件
                            sysTvArticleContentState();
                            PopUpManager.dismiss();

                            //保存选择的答案
                            //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                            //currPos对应的每个大题的小题的位置,单选题默认就一个小题
                            int choosePos = quesPos;
                            //是否如正确
                            boolean chooseResult = false;

                            if (rightAnswer.equals(content)) {
                                //用户作答正确
                                chooseResult = true;
                            } else {
                                //用户作答错误
                                chooseResult = false;
                            }

                            //回传当前提醒的TypeId,当前题型对应的是13
                            int typeId = 13;
                            BusInfo busInfo = new BusInfo();
                            busInfo.tkMsg = TkKeys.TKMsg;
                            busInfo.tkChoosePos = choosePos;
                            busInfo.tkChooseAnswer = content;
                            busInfo.tkChooseResult = chooseResult;
                            busInfo.typeId = typeId;
                            EventBus.getDefault().post(busInfo);
                        }
                    }
                });
            }
        });
    }

    /**
     * 初始化你的作答,正确答案,答案正确率和解析
     * 需要通过用户是否是已完成和未完成的状态来确定该部分的视图显示与隐藏,同时设置数据的数据源不一样
     * 该设置需要取已完成状态的数据源集合
     */
    private void initHasCompetedData() {
        List<ReadShowAnswerInfo> oldDatas = new ArrayList<>();
//        for (int i = 0; i < 4; i++) {
//            ReadShowAnswerInfo readShowAnswerInfo = new ReadShowAnswerInfo();
//            readShowAnswerInfo.progress = 10 * (i + 1);
//            oldDatas.add(readShowAnswerInfo);
//        }
//        ReadShowAnswerAdapter answerAdapter = new ReadShowAnswerAdapter(getContext(), oldDatas, R.layout.tk_lv_read_show_answer);

        //设置你的作答,正确答案,展示每个选项的正确率的进度条以及解析
        tv_own_answer.setText(articleInfo.chooseAnswer);
        tv_right_answer.setText(articleInfo.rightAnswer);
        tvParseAnswer.setText(articleInfo.explain);
        tv_answer_present.setText(articleInfo.proba);

    }

    /**
     * 点击事件
     */
    private abstract class TextClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#EC8628"));
        }
    }

}
